<?php

namespace Trawind\AliOSS\Plugins;
use Faker\Core\File;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Facades\Storage;
use League\Flysystem\Config;
use League\Flysystem\Plugin\AbstractPlugin;
class DownloadObject extends AbstractPlugin
{
    private $config;

    public function __construct($config)
    {
        $this->config = $config;
    }

    /**
     * Get the method name.
     *
     * @return string
     */
    public function getMethod()
    {
        return 'downloadObject';
    }

    public function handle($path, $size, $downloadDisk = 'local', array $options = []){
        $allOptions = [];
        while (true) {
            $size = $size - $this->config['size'] - 1;
            if ($size > 0) {
                $allOptions[] = [$size, $size + $this->config['size']];
            } else {
                $allOptions[] = [0, $size + $this->config['size']];
                break;
            }
        }
        $allOptions = array_reverse($allOptions);

        $downloadPath = storage_path() . '/' . $path;
        if (!file_exists($downloadPath)) {
            $dirPath = dirname($downloadPath);
            app(Filesystem::class)->ensureDirectoryExists($dirPath);
        }

        foreach ($allOptions as $option) {
            $options['Range'] = $option[0] . '-' . $option[1];
            $config = new Config($options);
            if (method_exists($this->filesystem, 'getConfig')) {
                $config->setFallback($this->filesystem->getConfig());
            }
            $partObject = $this->filesystem->getAdapter()->multiGetObject($path, $config);
            file_put_contents($downloadPath, $partObject['raw_contents'], FILE_APPEND);
        }

        return $downloadPath;
    }
}
